package com.px.baolaiapi.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.px.common.api.CommonPage;
import com.px.common.api.CommonResult;
import com.px.common.constant.Constant;
import com.px.common.execption.Asserts;
import com.px.mbg.mapper.SupplierInfoMapper;
import com.px.mbg.model.SupplierInfo;
import com.px.baolaiapi.page.CustomerPage;
import com.px.baolaiapi.service.ISupplierInfoService;
import com.px.baolaiapi.util.JwtTokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 供应商信息 服务实现类
 * </p>
 *
 * @author 品讯科技
 * @since 2022-05-19
 */
@Transactional
@Service
public class SupplierInfoServiceImpl extends ServiceImpl<SupplierInfoMapper, SupplierInfo> implements ISupplierInfoService {


    @Autowired
    private JwtTokenUtils jwtTokenUtils;


    /**
     * 通过组织ID查询供应商信息
     * 如果oid为-1或0，则查询全部
     *
     * @return {@link List <SupplierInfo>}
     */
    @Override
    public List<SupplierInfo> querySupplierInfoAll() {
        LambdaQueryWrapper<SupplierInfo> queryWrapper = Wrappers.lambdaQuery(SupplierInfo.class);

        LocalDateTime now = LocalDateTime.now();
        queryWrapper.eq(SupplierInfo::getIsEnabled, Constant.IS_ENABLED.ENABLE).le(SupplierInfo::getEffectiveDate, now).ge(SupplierInfo::getDisableDate, now);

        queryWrapper.orderByDesc(SupplierInfo::getUpdatedTime);
        queryWrapper.eq(SupplierInfo::getOrganizationId, jwtTokenUtils.getOrganizationId());

        return this.list(queryWrapper);
    }

    @Override
    public void synchronizedSupplierInfo() {

    }

    /**
     * 执行接口的逻辑
     *
     * @param datas mes交互数据
     * @return {@link CommonResult}
     */
    public CommonResult operationInterface(Object datas) {
        //[{"code":"s-code1","organizationName":"宝涞","u9Id":1,"organizationId":1,"organizationCode":"baolai","name":"供应商名称1"}]
        JSONArray jsonArray = JSONUtil.parseArray(datas);
        if (jsonArray.size() > 0) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                Long organizationId = jsonObject.getLong("organizationId");
                Long u9Id = jsonObject.getLong("u9Id");
                String code = jsonObject.getStr("code");
                String name = jsonObject.getStr("name");
                String shortName = jsonObject.getStr("shortName")==null ? "":jsonObject.getStr("shortName");
                String isEnabled = jsonObject.getStr("isEnabled");
                String effectiveDate = jsonObject.getStr("effectiveDate");
                String disableDate = jsonObject.getStr("disableDate");

                Page<SupplierInfo> infoPage = this.page(new Page<>(1, 1), new QueryWrapper<SupplierInfo>().lambda().eq(SupplierInfo::getOrganizationId,organizationId).eq(SupplierInfo::getU9Id, u9Id));
                List<SupplierInfo> records = infoPage.getRecords();
                if (CollectionUtil.isNotEmpty(records)) {
                    //变更
                    SupplierInfo supplierInfo = records.get(0);
                    supplierInfo.setCode(code);
                    supplierInfo.setName(name);
                    supplierInfo.setShortName(shortName);
                    supplierInfo.setIsEnabled(Integer.parseInt(isEnabled));
                    supplierInfo.setDisableDate(disableDate);
                    supplierInfo.setEffectiveDate(effectiveDate);
                    supplierInfo.setOrganizationId(organizationId);

                    if (!this.updateById(supplierInfo)) {
                        Asserts.fail("同步供应商信息失败");
                    }
                } else {
                    //新增
                    SupplierInfo supplierInfo = new SupplierInfo();

                    supplierInfo.setCode(code);
                    supplierInfo.setName(name);
                    supplierInfo.setShortName(shortName);
                    supplierInfo.setIsEnabled(Integer.parseInt(isEnabled));
                    supplierInfo.setDisableDate(disableDate);
                    supplierInfo.setEffectiveDate(effectiveDate);
                    supplierInfo.setOrganizationId(organizationId);
                    supplierInfo.setU9Id(u9Id);

                    if (!this.save(supplierInfo)) {
                        Asserts.fail("同步供应商信息失败");
                    }
                }
            }
            return CommonResult.success("");
        }
        return CommonResult.failed();
    }


    @Override
    public CommonPage querySupplierPage(CustomerPage customerPage) {
        LambdaQueryWrapper<SupplierInfo> queryWrapper = Wrappers.lambdaQuery(SupplierInfo.class);


        Long organizationId = jwtTokenUtils.getOrganizationId();
        queryWrapper.eq(SupplierInfo::getOrganizationId,organizationId);

        LocalDateTime now = LocalDateTime.now();
        queryWrapper.eq(SupplierInfo::getIsEnabled, Constant.IS_ENABLED.ENABLE).le(SupplierInfo::getEffectiveDate, now).ge(SupplierInfo::getDisableDate, now);


        queryWrapper.eq(SupplierInfo::getIsDelFlag, Constant.IS_ENABLED.ENABLE);
        String code = customerPage.getCode();
        if (StringUtils.isNotEmpty(code)) {
            queryWrapper.like(SupplierInfo::getCode, code);
        }
        String name = customerPage.getName();
        if (StringUtils.isNotEmpty(name)) {
            queryWrapper.like(SupplierInfo::getName, name);
        }
        String shortName = customerPage.getShortName();
        if (StringUtils.isNotEmpty(shortName)) {
            queryWrapper.like(SupplierInfo::getShortName, shortName);
        }
        queryWrapper.orderByDesc(SupplierInfo::getCreatedTime);
        CommonPage commonPage = CommonPage.restPage(this.page(new Page<SupplierInfo>(customerPage.getPageNum(), customerPage.getPageRow()), queryWrapper));

        return commonPage;
    }
}
